﻿using Common.Net;
using LitJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Common.WeiXin
{
    public class WeiXinAccessToken
    {
        /// <summary>
        /// token对象
        /// </summary>
        static AccessToken _accessToken;
        public static string accessToken
        {
            get
            {
                return GetAccessToken().token;
            }
        }

        public static void RefreshAccessToken()
        {
            GetAccessToken(false);
        }
        /// <summary>
        /// token锁
        /// </summary>
        private static object tokenLocker = new object();
        /// <summary>
        /// 获取access_token
        /// </summary>
        private static AccessToken GetAccessToken()
        {
            return GetAccessToken(false);
        }
        private static AccessToken GetAccessToken(bool forceRefresh)
        {
            lock (tokenLocker)
            {
                if (!forceRefresh)
                {
                    if(_accessToken != null && _accessToken.expires >= DateTime.Now)
                    {
                        return _accessToken;
                    }
                }
                string result= HttpRequestHelper.getContentUTF8(accessTokenUri);
                try
                {
                    JsonData json = JsonMapper.ToObject(result);
                    _accessToken = new AccessToken()
                    {
                        token = json["access_token"].ToString(),
                        expires = DateTime.Now.AddSeconds(int.Parse(json["expires_in"].ToString()) - 200)//避免受网络影响，过期时间提前200s                
                    };
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }

                return _accessToken;
            }
        }

        /// <summary>
        /// 获取服务号access_token地址
        /// </summary>
        public static readonly string accessTokenUri = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", WeiXinHelper.appId, WeiXinHelper.appSecret);
    }

    /// <summary>
    /// access_token对象
    /// </summary>
    class AccessToken
    {
        /// <summary>
        /// Token
        /// </summary>
        public string token { get; set; }
        /// <summary>
        /// 过期时间
        /// </summary>
        public DateTime expires { get; set; }
    }
}
